package cn.huijielong.modules.oss.cloud;

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.IOUtils;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.request.UploadFileRequest;
import com.qcloud.cos.sign.Credentials;
import cn.huijielong.common.exception.VSException;
import cn.huijielong.modules.oss.entity.Oss;

import net.sf.json.JSONObject;

public class QcloudCloudStorage extends CloudStorage {
	private COSClient client;
	public QcloudCloudStorage(Oss oss,String bucket){
        this.oss = oss;
        this.ossBucket=oss.getBucket(bucket);
        init();
	}
	private void init(){
    	Credentials credentials = new Credentials(oss.getQcloudAppId(), oss.getQcloudSecretId(),
    			oss.getQcloudSecretKey());
    	
    	//初始化客户端配置
        ClientConfig clientConfig = new ClientConfig();
        //设置bucket所在的区域，华南：gz 华北：tj 华东：sh
        clientConfig.setRegion(oss.getQcloudRegion());
        
    	client = new COSClient(clientConfig, credentials);
    }

    @Override
    public String upload(byte[] data, String path) {
        //腾讯云必需要以"/"开头
        if(!path.startsWith("/")) {
            path = "/" + path;
        }
        
        //上传到腾讯云
        UploadFileRequest request = new UploadFileRequest(ossBucket.getBucketName(), path, data);
        String response = client.uploadFile(request);

        JSONObject jsonObject = JSONObject.fromObject(response);
        if(jsonObject.getInt("code") != 0) {
            throw new VSException("文件上传失败，" + jsonObject.getString("message"));
        }

        return ossBucket.getDomain() + path;
    }

    @Override
    public String upload(InputStream inputStream, String path) {
    	try {
            byte[] data = IOUtils.toByteArray(inputStream);
            return this.upload(data, path);
        } catch (IOException e) {
            throw new VSException("上传文件失败", e);
        }
    }
	@Override
	public String getPrivateUrl(String targetUrl) {
		return null;
	}
	@Override
	public boolean deleteBatch(String... path) {
		// TODO Auto-generated method stub
		return false;
	}
	@Override
	public boolean deleteBatch(String bucket, String... path) {
		// TODO Auto-generated method stub
		return false;
	}
	@Override
	public void close() {
		// TODO Auto-generated method stub
		
	}

}
